package com.zmx.patientend.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.Toolbar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import com.zmx.patientend.MyApplication;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.BraceletDataAdapter;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.BraceletData;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.activity.BraceletDataActivity;
import com.zmx.patientend.view.activity.FamilyArchivesActivity;
import com.zmx.patientend.view.activity.LoginActivity;
import com.zmx.patientend.view.activity.PatientMessageActivity;
import com.zmx.patientend.view.activity.PatientMessageDetailsActivity;
import com.zmx.patientend.view.util.CustomToast;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.Activity.RESULT_OK;

public class InformationFragment extends Fragment {

    //需要的权限数组 读/写/相机
    private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

    private Button login_button;

    private int REQUEST_CODE_SCAN = 1;
    private RecyclerView reView;
    private SmartRefreshLayout refreshLayout;
    private BraceletDataAdapter adapter;
    private List<BraceletData> lists;
    private LinearLayout liLayout;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_information, container, false);

        //跳转相机动态权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

        login_button = view.findViewById(R.id.login_button);
        login_button.setOnClickListener(v -> {

            Intent intent = new Intent();
            intent.setClass(InformationFragment.this.getContext(), LoginActivity.class);
            startActivityForResult(intent, 10);

        });


        liLayout = view.findViewById(R.id.liLayout);
        liLayout.setOnClickListener(v -> {

            if (!MyApplication.isLogin_state()) {

                Intent intent = new Intent();
                intent.setClass(InformationFragment.this.getContext(), LoginActivity.class);
                startActivityForResult(intent, 10);

            } else {


                Intent intent = new Intent();
                intent.putExtra("logo", 0);
                intent.setClass(InformationFragment.this.getContext(), PatientMessageActivity.class);
                startActivityForResult(intent, 2);


            }

        });

        liLayout = view.findViewById(R.id.liLayout);
        reView = view.findViewById(R.id.reView);
        reView.setLayoutManager(new LinearLayoutManager(InformationFragment.this.getActivity()));
        adapter = new BraceletDataAdapter(InformationFragment.this.getActivity());
        reView.setAdapter(adapter);
        lists = new ArrayList<>();
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Intent intent = new Intent(InformationFragment.this.getActivity(), PatientMessageDetailsActivity.class);
                intent.putExtra("patient_id", lists.get(listPosition).getPatient_id()+"");
                startActivity(intent);

            }
        });

        // 开启自动加载功能
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {

            getInfo();

        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {

            refreshLayout.finishLoadMore(true);

        });

        return view;

    }

    String pid = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == RESULT_OK) {

            Bundle bundle = data.getExtras();
            if (bundle != null) {

                pid = bundle.getString("patient_id");

//                //页面返回时，弹出提示框，包括确认、取消按钮，提示文字
                AlertDialog.Builder builder = new AlertDialog.Builder(InformationFragment.this.getContext());
                builder.setTitle("选择添加手环方式");
                builder.setNegativeButton("手动填写设备号", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (pid == null) {

                            CustomToast.getInstance().showToastCustom(InformationFragment.this.getContext(), "未选择患者", Gravity.BOTTOM);
                            return;
                        }

                        alert_label("输入设备号", pid);

                    }
                });
                builder.setPositiveButton("扫描二维码", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //检查是否已经获得相机的权限
                        if (verifyPermissions(InformationFragment.this.getActivity(), PERMISSIONS_STORAGE[2]) == 0) {
                            ActivityCompat.requestPermissions(InformationFragment.this.getActivity(), PERMISSIONS_STORAGE, 3);
                        } else {
                            //已经有权限
                            Intent intent = new Intent(InformationFragment.this.getActivity(), CaptureActivity.class);
                            /*ZxingConfig是配置类
                             *可以设置是否显示底部布局，闪光灯，相册，
                             * 是否播放提示音  震动
                             * 设置扫描框颜色等
                             * 也可以不传这个参数
                             * */
                            ZxingConfig config = new ZxingConfig();
                            config.setPlayBeep(true);//是否播放扫描声音 默认为true
                            config.setShake(true);//是否震动  默认为true
                            config.setDecodeBarCode(true);//是否扫描条形码 默认为true
                            config.setReactColor(R.color.colorAccent);//设置扫描框四个角的颜色 默认为白色
                            config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
                            config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色
                            config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                            intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                            startActivityForResult(intent, REQUEST_CODE_SCAN);
                        }
                    }
                });
                builder.show();


            }

        } else if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {

                if (pid == null) {

                    CustomToast.getInstance().showToastCustom(InformationFragment.this.getContext(), "未选择患者", Gravity.BOTTOM);
                    return;
                }

                String content = data.getStringExtra(Constant.CODED_CONTENT);
                binding(content, pid);
            }
        }


    }


    //结果处理函数，当从secondActivity中返回时调用此函数
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if(requestCode==0 && resultCode==RESULT_OK){
//            Bundle bundle = data.getExtras();
//            String text =null;
//            if(bundle!=null)
//                text=bundle.getString("second");
//            Log.d("text",text);
//            editText.setText(text);
//        }
//    }

    public void alert_label(String text, String pid) {

        AlertDialog.Builder builder = new AlertDialog.Builder(InformationFragment.this.getContext());

        LayoutInflater factory = LayoutInflater.from(InformationFragment.this.getContext());//提示框
        final View view = factory.inflate(R.layout.dialog_edit, null);//这里必须是final的
        final EditText et = view.findViewById(R.id.editText);
        et.setHint(text);
        builder.setTitle(text);

        final AlertDialog dialog = builder.create();
        dialog.setView(view);

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(et.getText().toString())) {

                    binding(et.getText().toString(), pid);
                    dialog.dismiss();

                } else {

                    CustomToast.getInstance().showToastCustom(InformationFragment.this.getContext(), "非法输入", Gravity.BOTTOM);

                }

            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();

        if (!MyApplication.isLogin_state()) {

            liLayout.setVisibility(View.GONE);
            login_button.setVisibility(View.VISIBLE);


        } else {

            login_button.setVisibility(View.GONE);
            liLayout.setVisibility(View.VISIBLE);
            //触发自动刷新
            refreshLayout.autoRefresh();


        }

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        lists.clear();
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());

                        if (jsonObject.getInt("code") == 1) {


                            JSONArray array = jsonObject.getJSONArray("data");
                            Gson gson = new Gson();
                            for (int i = 0; i < array.length(); i++) {

                                BraceletData bd = gson.fromJson(array.getJSONObject(i).toString(), BraceletData.class);
                                lists.add(bd);

                            }

                        }

                        adapter.setListAndNotifyDataSetChanged(lists);//就是设置list然后刷新
                        refreshLayout.finishRefresh(true);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        CustomToast.getInstance().showToastCustom(InformationFragment.this.getContext(), object.getString("msg"), Gravity.BOTTOM);
                        if (object.getInt("code") == 1){
                            getInfo();
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };

    /**
     * 检查是否有对应权限
     *
     * @param activity   上下文
     * @param permission 要检查的权限
     * @return 结果标识
     */
    public int verifyPermissions(Activity activity, java.lang.String permission) {
        int Permission = ActivityCompat.checkSelfPermission(activity, permission);
        if (Permission == PackageManager.PERMISSION_GRANTED) {

            return 1;
        } else {
            return 0;
        }
    }


    //获取血压数据
    public void getInfo() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(null)));
        params.put("token", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getInfo");
        params.put("data[]", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watch/", params, handler, 1, 404);

    }

    //签名
    public String sing(List<String> list) {

        StringBuilder requestparams = new StringBuilder();
        requestparams.append(MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, "") +
                MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.role, "") +
                System.currentTimeMillis() / 1000 + MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.password, ""));

        if (list != null) {
            for (String s : list) {
                requestparams.append(s);
            }
        }
        return requestparams.toString();

    }


    public void binding(String devicel, String pid) {

        List<String> l = new ArrayList<>();
        l.add(devicel);
        l.add(pid);

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this.getContext()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "binding");
        params.put("data[devicel]", devicel);
        params.put("data[patient_id]", pid);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watch/", params, handler, 2, 404);

    }

}
